package cn.tedu.mall.search.service.impl;

import cn.tedu.mall.common.restful.JsonPage;
import cn.tedu.mall.pojo.product.model.Spu;
import cn.tedu.mall.pojo.search.entity.SpuForElastic;
import cn.tedu.mall.product.service.front.IForFrontSpuService;
import cn.tedu.mall.search.repository.SpuRepository;
import cn.tedu.mall.search.service.ISearchService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.ArrayList;

@Slf4j
@Service
public class SearchServiceImpl implements ISearchService {

    @DubboReference
    private IForFrontSpuService dubboFrontSpuService;

    @Autowired
    private SpuRepository spuRepository;


    @Override
    public void loadSpuByPage() {
        //页码
        int page=1;
        //每页条数
        int pageSize=10;
        //总页数,作为分页加载的条件
        int pages=0;

        do {
            JsonPage<Spu> spuByPage = dubboFrontSpuService.getSpuByPage(page, pageSize);
            //ES中需要的类型List<SpuForElastic>
            ArrayList<SpuForElastic> esSpus = new ArrayList<SpuForElastic>();
            for (Spu spu : spuByPage.getList()) {
                //将Spu对象转换成SpuForElastic
                SpuForElastic spuForElastic = new SpuForElastic();
                BeanUtils.copyProperties(spu,spuForElastic);
                esSpus.add(spuForElastic);
            }
            spuRepository.saveAll(esSpus);
            log.info("成功加载第{}页数据到es中",page);
            pages=spuByPage.getTotalPage();//总页码数
            page++;
        } while (page<=pages);
    }

    @Override
    public JsonPage<SpuForElastic> search(String keyword, Integer page, Integer pageSize) {
        //Spring Data ES 第一页的下标是0
        Page<SpuForElastic> spuForElastics = spuRepository.querySearch(keyword, PageRequest.of(page - 1, pageSize));
        JsonPage<SpuForElastic> jsonPage = new JsonPage<>();
        jsonPage.setPage(page);
        jsonPage.setPageSize(pageSize);
        jsonPage.setTotalPage(spuForElastics.getTotalPages());//总页数
        jsonPage.setTotal(spuForElastics.getTotalElements());//总条数
        jsonPage.setList(spuForElastics.getContent());//分页数据
        return jsonPage;
    }
}
